const { readFile } = require("fs/promises");
const path = require("path");
let cfg;

function getSpeakers() {
  return readFile(path.join(__dirname, "sounds.json")).then(
    (val) =>
      new Promise((resolve, reject) => {
        resolve(JSON.parse(val));
      })
  );
}

function updateCfg(newCfg) {
  return new Promise((resolve, reject) => {
    try {
      cfg = newCfg;
      resolve();
    } catch (error) {
      reject(error);
    }
  });
}

function synth(text, speaker) {
  console.log({ text: text, speaker: speaker, ...cfg });
  if (!cfg.token || !cfg.appid) {
    return new Promise((resolve, reject) => {
      reject(new Error("Please Set Config"));
    });
  } else {
    return fetch("https://openspeech.bytedance.com/api/v1/tts", {
      headers: { Authorization: `Bearer;${cfg.token}` },
      method: "POST",
      body: JSON.stringify({
        app: {
          appid: cfg.appid,
          token: "access_token",
          cluster: "volcano_tts",
        },
        user: {
          uid: "uid123",
        },
        audio: {
          voice_type: speaker,
          encoding: "mp3",
          compression_rate: 1,
          rate: 24000,
          bits: 16,
          channel: 1,
          speed_ratio: 1.0,
          volume_ratio: 1.0,
          pitch_ratio: 1.0,
          emotion: "happy",
          language: "cn",
        },
        request: {
          reqid: "uuid",
          text: text,
          text_type: "plain",
          operation: "query",
          silence_duration: "125",
          with_frontend: "1",
          frontend_type: "unitTson",
          pure_english_opt: "1",
        },
      }),
    }).then((res) => res.json());
  }
}

module.exports = {
  getSpeakers: getSpeakers,
  updateCfg: updateCfg,
  synth: synth,
};
